package com.yjs.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.yjs.bean.UserInfo;
import com.yjs.service.UserInfoService;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


/**
 * @author yjs
 * @create 2020-09-16-10:45
 * 用户controller层
 */
@Controller
public class UserController {

    //注入userservice层
    @Autowired
    UserInfoService userInfoService;

    //跳转推出登陆请求操作
    @GetMapping("/")
    public String toLogin(){
        return "login";
    }

    //处理登陆操作
    @PostMapping("/user/login")
    public String login(UserInfo userInfo, Map<String,Object> map, HttpSession session){
        UserInfo login = userInfoService.login(userInfo);
        if (login!=null){
            session.setAttribute("loginUser",login.getUsername());
            return "redirect:/main.html";
        }else {
            map.put("msg","用户名或密码错误");
            return "login";
        }
    }
    //处理注册操作
    @PostMapping("/user/register")
    public String register(UserInfo userInfo){
        userInfoService.register(userInfo);
        return "login";
    }

    //查询个人信息并返回
    @GetMapping("/personinfo")
    public String getOneUser(HttpSession session, Model model){
        String user = (String) session.getAttribute("loginUser");
        UserInfo oneUser = userInfoService.getOneUser(user);
        model.addAttribute("oneUser",oneUser);
        return "user/personinfo";
    }
    //修改个人信息
    @PutMapping("/user/updUser")
    public String updUser(UserInfo userInfo){
//        System.out.println(userInfo);
        userInfoService.updUser(userInfo);
        return "redirect:/main.html";
    }


    //修改密码
    @PutMapping("/updPwd")
    public String updPwd(String oldpwd,String confirmpwd,HttpSession session,Model model){
        String user = (String) session.getAttribute("loginUser");
        UserInfo oneUser = userInfoService.getOneUser(user);
        if(oneUser.getPassword().equals(oldpwd)){
            userInfoService.updPwd(oneUser.getUid(),confirmpwd);
            session.removeAttribute("loginUser");
            return "redirect:/toLogin";
        }
        model.addAttribute("loginerror","密码不正确，请重新输入");
        return "user/editpwd";
    }

}
